package com.quasar.hpatient.module.home_temperature;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.quasar.hpatient.R;
import com.quasar.hpatient.api.HttpClient;
import com.quasar.hpatient.api.HttpParams;
import com.quasar.hpatient.bean.home_inspection.CalendarBean;
import com.quasar.hpatient.bean.home_inspection.CalendarTBean;
import com.quasar.hpatient.bean.home_temperature.TemperatureItemBean;
import com.quasar.hpatient.dialog.CalendarDialog;
import com.quasar.hpatient.module.home_daily.HomeDailyActivity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import io.reactivex.Observable;
import lib.quasar.base.frame.BasePresenter;
import lib.quasar.base.frame.OnModelAcceptChangeListener;
import lib.quasar.base.frame.OnModelChangeListener;
import lib.quasar.context.BaseApp;
import lib.quasar.recycler.BaseCommonAdapter;
import lib.quasar.recycler.holder.RecyclerHolder;
import lib.quasar.recycler.manager.CrashLinearLayoutManager;
import lib.quasar.util.DimenUtil;
import lib.quasar.util.LogUtil;
import lib.quasar.util.ToastUtil;
import lib.quasar.widget.chart.ChartView;
import okhttp3.RequestBody;

/**
 * description: 首页 ==> 体温
 * created by kalu on 2018/3/29 9:03
 */
public class TemperaturePresenter implements BasePresenter {

    private final LinkedList<TemperatureItemBean> mDatas = new LinkedList();

    final void initTime(final TemperatureView view, TextView dates, TextView times) {

        if (null != dates) {
            view.setText(dates, getCalendar());
        }

        if (null != times) {
            view.setText(times, getMinuteLittle());
        }
    }

    final void initList(final TemperatureView view, RecyclerView recycler, boolean mulit) {

        if (null == view || null == recycler) return;

        final BaseCommonAdapter<TemperatureItemBean> adapter = new BaseCommonAdapter<TemperatureItemBean>(mDatas, R.layout.activity_home_temperature_child) {

            @Override
            protected void onNext(final RecyclerHolder holder, final TemperatureItemBean model, final int position) {

                view.setText(holder, R.id.home_temperature_child_time, model.getLogtime(!mulit));
                view.setText(holder, R.id.home_temperature_child_input, model.getRecord_value());
                view.setText(holder, R.id.home_temperature_child_state, model.getState());
                view.setTextColor(holder, R.id.home_temperature_child_state, model.getColor());
                //体温值颜色控制
                // view.setTextColor(holder, R.id.home_temperature_child_input, model.getTemperatureColor());

                if (mulit) return;
                String record_value = model.getRecord_value();
                holder.setOnClickListener(R.id.home_temperature_child_input, v -> view.showInput(record_value, position));
                holder.setOnLongClickListener(R.id.home_temperature_child_input, v -> {
                    view.showDelete(position);
                    return true;
                });
                holder.setOnLongClickListener(R.id.home_temperature_child_time, v -> {
                    view.showDelete(position);
                    return true;
                });
                holder.setOnLongClickListener(R.id.home_temperature_child_state, v -> {
                    view.showDelete(position);
                    return true;
                });
            }
        };

        final View head = LayoutInflater.from(BaseApp.getContext()).inflate(R.layout.activity_home_temperature_head, null);
        final RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DimenUtil.dp2px(40));
        head.setLayoutParams(params);
        adapter.addHead(head);

        // adapter.setNullView(BaseApp.getContext(), R.layout.layout_recycler_loading);
        final CrashLinearLayoutManager manager = new CrashLinearLayoutManager(BaseApp.getContext());
        view.setRecycler(recycler, adapter, manager);
    }

    final void schemelList(CalendarDialog dialog, String year, String month, String minDay, String maxDay) {

        final HashMap<String, Object> map = new HashMap<>();
        map.put(BEGIN_DATE, BaseApp.getResource().getString(R.string.date_calendar, year, month, minDay));
        map.put(END_DATE, BaseApp.getResource().getString(R.string.date_calendar, year, month, maxDay));
        map.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_TEMPERATURE);
        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_3_9);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().schemeTList(params);

        request(observable, new OnModelAcceptChangeListener<List<CalendarTBean>>() {
            @Override
            public void modelSucc(List<CalendarTBean> list) {
                dialog.getCalendarView().setScheme(list);
            }
        });
    }

    final void temperatureList(final TemperatureView view, RecyclerView recycler, ChartView chart, boolean mulit) {

        if (null == view || null == chart || null == recycler)
            return;

        final String dateStr = view.getDate();
        if (TextUtils.isEmpty(dateStr)) {
            view.toast("时间格式不正确");
            return;
        }

        // 清空列表
        mDatas.clear();
        view.refreshList(recycler);

        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.RECORD_DATE, getDate(dateStr));
        map.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_TEMPERATURE);

        if (mulit) {

            map.put(HttpParams.NUM, "10");
            final RequestBody params = createParams(map, HttpParams.DATA_TYPE_3_3);
            final Observable observable = HttpClient.getSingleHolder().getHttpService().temperatureListMulit(params);

            request(observable, new OnModelAcceptChangeListener<List<HashMap<String, ArrayList<TemperatureItemBean>>>>() {

                @Override
                public void modelFail() {
                    view.setChartNull(chart, R.string.chart_null);
                }

                @Override
                public void modelStart() {
                    mDatas.clear();
                }

                @Override
                public void modelSucc(List<HashMap<String, ArrayList<TemperatureItemBean>>> result) {

                    if (null == result || result.size() == 0) return;

                    for (HashMap<String, ArrayList<TemperatureItemBean>> map : result) {

                        if (null == map || map.size() == 0) continue;

                        final Collection<ArrayList<TemperatureItemBean>> collection = map.values();
                        if (null == collection || collection.size() == 0) continue;

                        for (ArrayList<TemperatureItemBean> list : collection) {

                            if (collection.size() == 1 && (null == list || list.size() == 0))
                                continue;

                            for (TemperatureItemBean model : list) {

                                if (collection.size() == 1 && list.size() == 1 && null == model)
                                    continue;
                                mDatas.add(model);
                            }
                        }
                        Collections.sort(mDatas, (o1, o2) -> o2.getRecord_datetime().compareToIgnoreCase(o1.getRecord_datetime()));

                    }
                }

                @Override
                public void modelComplete() {

                    if (null == mDatas || mDatas.size() == 0) {
                        view.setChartNull(chart, R.string.chart_null);
                    } else {
                        view.setChart(chart, mDatas);
                    }
                    view.refreshList(recycler);
                }
            });

        } else {

            final RequestBody params = createParams(map, HttpParams.DATA_TYPE_3_2);
            final Observable observable = HttpClient.getSingleHolder().getHttpService().temperatureList(params);

            request(observable, new OnModelAcceptChangeListener<HashMap<String, ArrayList<TemperatureItemBean>>>() {
                @Override
                public void modelFail() {
                    view.setChartNull(chart, R.string.chart_null);
                }

                @Override
                public void modelStart() {
                    mDatas.clear();
                }

                @Override
                public void modelSucc(HashMap<String, ArrayList<TemperatureItemBean>> result) {

                    if (null == result) {
                        modelFail();
                        return;
                    }

                    final Collection<ArrayList<TemperatureItemBean>> collection = result.values();
                    if (null == collection || collection.size() == 0) {
                        modelFail();
                        return;
                    }

                    for (ArrayList<TemperatureItemBean> list : collection) {

                        if (collection.size() == 1 && (null == list || list.size() == 0)) {
                            modelFail();
                            return;
                        }

                        for (TemperatureItemBean model : list) {

                            if (collection.size() == 1 && list.size() == 1 && null == model) {
                                modelFail();
                                return;
                            }
                            mDatas.add(model);
                        }
                    }
                    Collections.sort(mDatas, (o1, o2) -> o2.getRecord_datetime().compareToIgnoreCase(o1.getRecord_datetime()));

                }

                @Override
                public void modelComplete() {

                    if (null == mDatas || mDatas.size() == 0) {
                        view.setChartNull(chart, R.string.chart_null);
                    } else {
                        view.setChart(chart, mDatas);
                    }
                    view.refreshList(recycler);
                }
            });
        }
    }

    final void deleteTemperature(final TemperatureView view, ChartView chart, RecyclerView recycler, int position) {

        final TemperatureItemBean old = mDatas.get(position);
        mDatas.remove(position);

        // step:3
        String warnSign = "0";
        for (TemperatureItemBean temp : mDatas) {
            if ("0".equals(warnSign) && temp.isWarning()) {
                warnSign = "1";
            }
        }

        final HashMap<String, List<TemperatureItemBean>> push = new HashMap<>();
        push.put(getDate(view.getDate()), mDatas);

        HashMap<String, Object> params2 = new HashMap<>();
        params2.put(HttpParams.RECORD_DATE, getDate(view.getDate()));
        if (mDatas.size() == 0)
            params2.put(HttpParams.DATAS, "");
        else
            params2.put(HttpParams.DATAS, push);
        params2.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_TEMPERATURE);
        params2.put(HttpParams.T_WARN_SIGN, warnSign);

        final RequestBody params1 = createParams(params2, HttpParams.DATA_TYPE_3_1);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().saveTemperature(params1);

        request(observable, new OnModelChangeListener() {

            @Override
            public void modelFail() {
                mDatas.add(position, old);
                ToastUtil.showToast("删除体温失败");
            }

            @Override
            public void modelSucc() {
                view.setChart(chart, mDatas);
                view.refreshList(recycler);
                ToastUtil.showToast("删除体温成功");
            }
        });
    }

    final void editTemperature(final TemperatureView view, ChartView chart, RecyclerView recycler, String input, int position) {

        try {
            final float temp = Float.parseFloat(input);
            if (temp < 35f || temp > 45f) {
                view.toast(R.string.home_temperature_waining);
                return;
            }
        } catch (Exception e) {
            LogUtil.e("", e.getMessage(), e);
        }

        final String dateStr = view.getDate();

        final TemperatureItemBean model = mDatas.get(position);
        final String old = model.getRecord_value();
        model.setRecord_value(input);

        // step:3
        String warnSign = "0";
        for (TemperatureItemBean temp : mDatas) {
            if ("0".equals(warnSign) && temp.isWarning()) {
                warnSign = "1";
            }
        }

        final HashMap<String, List<TemperatureItemBean>> push = new HashMap<>();
        push.put(getDate(dateStr), mDatas);

        HashMap<String, Object> params2 = new HashMap<>();
        params2.put(HttpParams.RECORD_DATE, getDate(dateStr));
        if (mDatas.size() == 0)
            params2.put(HttpParams.DATAS, "");
        else
            params2.put(HttpParams.DATAS, push);
        params2.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_TEMPERATURE);
        params2.put(HttpParams.T_WARN_SIGN, warnSign);
        final RequestBody params1 = createParams(params2, HttpParams.DATA_TYPE_3_1);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().saveTemperature(params1);

        request(observable, new OnModelChangeListener() {

            @Override
            public void modelFail() {
                model.setRecord_value(old);
                ToastUtil.showToast("修改体温失败");
            }

            @Override
            public void modelSucc() {
                view.setChart(chart, mDatas);
                view.refreshList(recycler);
                ToastUtil.showToast("修改体温成功");
            }
        });
    }

    final void saveTemperature(final TemperatureView view, ChartView chart, RecyclerView recycler, EditText edit) {

        final String date = view.getDate();
        if (TextUtils.isEmpty(date)) {
            view.toast(R.string.home_temperature_waining2);
            return;
        }

        final String time = view.getTime();
        if (TextUtils.isEmpty(time)) {
            view.toast(R.string.home_temperature_waining2);
            return;
        }

        final String tempStr = view.getTemperature();
        if (TextUtils.isEmpty(tempStr)) {
            view.toast(R.string.home_temperature_waining);
            edit.getText().clear();
            return;
        }
        try {
            final float temp = Float.parseFloat(tempStr);
            if (temp < 35f || temp > 45f) {
                view.toast(R.string.home_temperature_waining);
                edit.getText().clear();
                return;
            }
        } catch (Exception e) {
            LogUtil.e("", e.getMessage(), e);
        }

        // step0
        String warnSign = "0";
//        for (TemperatureItemBean model : mDatas) {
//
//            if ("0".equals(warnSign) && model.isWarning()) {
//                warnSign = "1";
//            }
//        }
        // step1
        final TemperatureItemBean news = new TemperatureItemBean();
        news.setRecord_datetime(getDateTemperature(date, time));
        news.setRecord_value(tempStr);
        final String itemdose = BaseApp.getContext().getResources().getString(R.string.home_temperature_units);
        news.setRecord_dose(itemdose);
        // step2
        mDatas.addFirst(news);

        for (TemperatureItemBean model : mDatas) {

            if ("0".equals(warnSign) && model.isWarning()) {
                warnSign = "1";
            }
        }
        // step3
        Collections.sort(mDatas, (o1, o2) -> o2.getRecord_datetime().compareToIgnoreCase(o1.getRecord_datetime()));
        // step4
        final HashMap<String, List<TemperatureItemBean>> list = new HashMap<>();
        list.put(getDate(date), mDatas);
        // step5
        HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.RECORD_DATE, getDate(date));
        map.put(HttpParams.DATAS, list);
        map.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_TEMPERATURE);
        map.put(HttpParams.T_WARN_SIGN, warnSign);
        // step6
        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_3_1);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().saveTemperature(params);

        request(observable, new OnModelChangeListener() {

            @Override
            public void modelFail() {
                mDatas.remove(news);
                view.toast("添加体温失败");
            }

            @Override
            public void modelSucc() {
                edit.getText().clear();
                edit.clearFocus();
                view.setChart(chart, mDatas);
                view.refreshList(recycler);
                view.toast("添加体温成功");
            }
        });
    }

    Intent getResult(TemperatureView view, int position) {

        if (position != -1 && mDatas.size() != 0) {
            final Intent intent = new Intent();
            intent.putExtra(HomeDailyActivity.POSITION, position);
            final TemperatureItemBean model = mDatas.get(0);
            intent.putExtra(HomeDailyActivity.INPUT, String.valueOf(model.getValue()));
            return intent;
        }
        return null;
    }

    @Override
    public void recycler() {
    }
}
